package com.bhs.sansong.ui.main;

import static com.bhs.sansong.base.Constants.serviceTel;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.ArrayMap;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bhs.sansong.R;
import com.bhs.sansong.adapter.AddressBookAdapter;
import com.bhs.sansong.adapter.MenuAdapter;
import com.bhs.sansong.base.BaseBean;
import com.bhs.sansong.base.BaseFragment;
import com.bhs.sansong.bean.AdvertisingBean;
import com.bhs.sansong.bean.MenuBean;
import com.bhs.sansong.bean.UserInfo;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.ui.discountCoupon.CouponReceivedActivity;
import com.bhs.sansong.ui.mine.CommonProblemActivity;
import com.bhs.sansong.ui.mine.FeedbackActivity;
import com.bhs.sansong.ui.mine.HistoricalFootprintActivity;
import com.bhs.sansong.ui.mine.InvitationCodeActivity;
import com.bhs.sansong.ui.mine.MyCollectActivity;
import com.bhs.sansong.ui.mine.PersonalInformationActivity;
import com.bhs.sansong.ui.other.TestActivity;
import com.bhs.sansong.ui.setting.SettingActivity;
import com.bhs.sansong.ui.shipments.AddressBookActivity;
import com.bhs.sansong.ui.wallet.BalanceActivity;
import com.bhs.sansong.ui.wallet.MyRedEnvelopeActivity;
import com.bhs.sansong.ui.wallet.TotalBillActivity;
import com.bhs.sansong.utils.FastCilckOneUtil;
import com.bhs.sansong.utils.MyUtils;
import com.bhs.sansong.utils.SharedPreferencesUtils;
import com.bhs.sansong.utils.ToastUtil;
import com.bhs.sansong.view.AutoScrollViewPager;
import com.bhs.sansong.view.BannerIndicator;
import com.bhs.sansong.view.ViewPagerAdapter;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;


public class MineFragment extends BaseFragment implements View.OnClickListener, NetCallBack {

    private ShapeableImageView mIvHead;
    private TextView mTvNickName;
    private TextView mTvPhone;
    private LinearLayout mLlBalance;
    private TextView mTvRemainingSum;
    private LinearLayout mLlDiscountCoupon;
    private TextView mTvDiscountCoupon;
    private LinearLayout mLlEnvelope;
    private TextView mTvEnvelope;
    private RelativeLayout mRlCarousel;
    private AutoScrollViewPager mVpCarousel;
    private BannerIndicator mIndicator;
    private RecyclerView mRvFunction;
    private RecyclerView mRvFeedback;
    private String invite_code;

    public static MineFragment newInstance() {
        return new MineFragment();
    }

    @Override
    public int initLayout() {
        return R.layout.fragment_mine;
    }

    @Override
    public void initView(View root) {

    }

    @Override
    public void prestrain() {
        super.prestrain();
        View root = view;
        root.findViewById(R.id.iv_scan_code).setOnClickListener(this);
        root.findViewById(R.id.iv_set).setOnClickListener(this);
        root.findViewById(R.id.cl_personal_information).setOnClickListener(this);
        mIvHead = root.findViewById(R.id.iv_head);
        mTvNickName = root.findViewById(R.id.tv_nick_name);
        mTvPhone = root.findViewById(R.id.tv_phone);
        mLlBalance = root.findViewById(R.id.ll_balance);
        mTvRemainingSum = root.findViewById(R.id.tv_remaining_sum);
        mLlDiscountCoupon = root.findViewById(R.id.ll_discount_coupon);
        mTvDiscountCoupon = root.findViewById(R.id.tv_discount_coupon);
        mLlEnvelope = root.findViewById(R.id.ll_envelope);
        mTvEnvelope = root.findViewById(R.id.tv_envelope);
        mRlCarousel = root.findViewById(R.id.rl_carousel);
        mVpCarousel = root.findViewById(R.id.vp_carousel);
        mIndicator = root.findViewById(R.id.indicator);
        mRvFunction = root.findViewById(R.id.rv_function);
        mRvFeedback = root.findViewById(R.id.rv_feedback);
        mLlBalance.setOnClickListener(this);
        mLlDiscountCoupon.setOnClickListener(this);
        mLlEnvelope.setOnClickListener(this);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initData() {
        List<MenuBean> menuBeanList = new ArrayList<>();
        menuBeanList.add(new MenuBean("地址簿", R.mipmap.ic_address_book));
       // menuBeanList.add(new MenuBean("发票报销", R.mipmap.ic_invoice));
        menuBeanList.add(new MenuBean("我的收藏", R.mipmap.ic_collect));
        menuBeanList.add(new MenuBean("我的评论", R.mipmap.ic_my_comment));
        menuBeanList.add(new MenuBean("历史足迹", R.mipmap.ic_historical_footprint));
        menuBeanList.add(new MenuBean("账单", R.mipmap.ic_bill));
       // menuBeanList.add(new MenuBean("物流入驻", R.mipmap.ic_logistics_settlement));

        MenuAdapter menuAdapter = new MenuAdapter(R.layout.item_menu2, menuBeanList);
        mRvFunction.setAdapter(menuAdapter);
        mRvFunction.setLayoutManager(new GridLayoutManager(activity, 4));

        List<MenuBean> menuBeanList2 = new ArrayList<>();
        menuBeanList2.add(new MenuBean("常见问题", R.mipmap.ic_fqa));
        menuBeanList2.add(new MenuBean("联系客服", R.mipmap.ic_service2));
        menuBeanList2.add(new MenuBean("意见反馈", R.mipmap.ic_feedback));

        MenuAdapter menuAdapter2 = new MenuAdapter(R.layout.item_menu2, menuBeanList2);
        mRvFeedback.setAdapter(menuAdapter2);
        mRvFeedback.setLayoutManager(new GridLayoutManager(activity, 4));

        menuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (FastCilckOneUtil.isFastClick()) {
                    return;
                }
                if (menuBeanList.get(position).getMenuName().equals("地址簿")) {
                    startActivity(new Intent(getContext(), AddressBookActivity.class)
                            .putExtra("type",2));
                } else if (menuBeanList.get(position).getMenuName().equals("账单")) {
                    startActivity(new Intent(getContext(), TotalBillActivity.class));
                } else if (menuBeanList.get(position).getMenuName().equals("我的收藏")) {
                    startActivity(new Intent(getContext(), MyCollectActivity.class));
                } else if (menuBeanList.get(position).getMenuName().equals("我的评论")) {
                    //startActivity(new Intent(getContext(), TestActivity.class));
                }else if (menuBeanList.get(position).getMenuName().equals("历史足迹")) {
                    startActivity(new Intent(getContext(), HistoricalFootprintActivity.class));
                }
            }
        });

        menuAdapter2.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (FastCilckOneUtil.isFastClick()) {
                    return;
                }
                if (menuBeanList2.get(position).getMenuName().equals("常见问题")) {
                    startActivity(new Intent(getActivity(), CommonProblemActivity.class));
                } else if (menuBeanList2.get(position).getMenuName().equals("联系客服")) {
                    // startActivity(new Intent(getActivity(), CustomerServiceActivity.class));
                    MyUtils.callPhone(getContext(), serviceTel);
                } else if (menuBeanList2.get(position).getMenuName().equals("意见反馈")) {
                    startActivity(new Intent(getActivity(), FeedbackActivity.class));
                }
            }
        });
        Map<String, String> map = new ArrayMap<>();
        map.put("platform", "cargo");
        map.put("city", "1");
        map.put("ad_sign", "AppCargoPersonal");
        networkRequest(netApi.get_ad_list(map), this, 9527);
    }

    @Override
    public void onResumes() {
        super.onResumes();
        networkRequest(netApi.get_user_info(), this, 888);
        if (mVpCarousel != null) {
            mVpCarousel.startAutoPlay();
        }
    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_discount_coupon:
                startActivity(new Intent(getContext(), CouponReceivedActivity.class));
                break;
            case R.id.iv_set:
                startActivity(new Intent(getContext(), SettingActivity.class));
                break;
            case R.id.ll_envelope:
                startActivity(new Intent(getContext(), MyRedEnvelopeActivity.class)
                        .putExtra("invite_code", invite_code));
                break;
            case R.id.ll_balance:
                startActivity(new Intent(getContext(), BalanceActivity.class)
                        .putExtra("balance", mTvRemainingSum.getText().toString()));
                break;
            case R.id.iv_scan_code:
                startActivity(new Intent(getContext(), InvitationCodeActivity.class)
                        .putExtra("invite_code", invite_code));
                break;
            case R.id.cl_personal_information:
                startActivity(new Intent(getContext(), PersonalInformationActivity.class));
                break;
        }

    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 9527) {
            AdvertisingBean infoBean = new Gson().fromJson(json, AdvertisingBean.class);
            if (infoBean.isStatus() && !MyUtils.isEmpty(infoBean.getData().getList())) {
                ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(infoBean.getData().getList(), getActivity(),1,true);
                mVpCarousel.setAdapter(pagerAdapter);
                mIndicator.setUpWidthViewPager(mVpCarousel, infoBean.getData().getList().size());
            }
        } else if (requestCode == 888) {
            UserInfo userInfo = new Gson().fromJson(json, UserInfo.class);
            if (userInfo.isStatus()) {
                setData(userInfo);
            }
        }
    }

    private void setData(UserInfo userInfo) {
        UserInfo.DataDTO.UserInfoDTO data = userInfo.getData().getUser_info();
        mTvRemainingSum.setText(data.getMoney01());
        mTvPhone.setText(data.getMobile());
        mTvDiscountCoupon.setText(userInfo.getData().getCoupon_count());
        mTvEnvelope.setText(data.getMoney02());
        Glide.with(getContext()).load(data.getHeaderpic()).into(mIvHead);
        SharedPreferencesUtils.saveString(getContext(), "face", data.getHeaderpic());
        SharedPreferencesUtils.saveString(getContext(), "niceName", data.getNickname());
        SharedPreferencesUtils.saveString(getContext(), "circle_pic", data.getCircle_pic());
        SharedPreferencesUtils.saveBoolean(getContext(), "is_approve", data.getIs_approve()==1);
        invite_code = data.getInvite_code();
        mTvNickName.setText(data.getNickname());

    }

    @Override
    public void onFailure(int requestCode) {

    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onEvent(UserInfo event) {
        setData(event);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mVpCarousel != null) {
            mVpCarousel.stopAutoPlay();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}